package ru.spbau.database.group3.parser;

import ru.spbau.database.group3.queryEvaluator.CreateIndexInstruction;
import ru.spbau.database.group3.queryEvaluator.Instruction;
import ru.spbau.database.group3.queryEvaluator.ErrorInstruction;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * User: stas
 * Date: 1/29/13
 * Time: 7:26 PM
 */
public class CreateIndexCmd extends abstractCmd {
    public CreateIndexCmd() {
        super(StringConstants.CREATE_INDEX);
    }

    @Override
    public Instruction process(String cmd) throws IOException {
        try {
            String indexName = getIndexName(cmd);
            String tableName = getTableName(cmd);
            List<String> cols = getCols(cmd);
            List<String> orders = getOrders(cmd);
            String type = getType(cmd);
            return new CreateIndexInstruction(indexName, tableName, cols, orders, type);
        } catch (IndexOutOfBoundsException e) {
            return new ErrorInstruction(e.getMessage());
        }
    }

    private String getType(String cmd) {
        int begin = cmd.indexOf(StringConstants.USING) + StringConstants.USING.length();
        return cmd.substring(begin).trim();
    }

    private List<String> getOrders(String cmd) {
        int begin = cmd.indexOf("(", cmd.indexOf(StringConstants.ON)) + 1;
        int end = cmd.lastIndexOf(")");
        String[] col_ord = cmd.substring(begin, end).trim().split(",");
        ArrayList<String> orders = new ArrayList<String>();
        for(String i : col_ord) {
            orders.add(i.trim().split(" ").length > 1 ? i.trim().split(" ")[1] : StringConstants.ASC);
        }
        return orders;
    }

    private List<String> getCols(String cmd) {
        int begin = cmd.indexOf("(", cmd.indexOf(StringConstants.ON)) + 1;
        int end = cmd.lastIndexOf(")");
        String[] col_ord = cmd.substring(begin, end).trim().split(",");
        ArrayList<String> names = new ArrayList<String>();
        for(String i : col_ord) {
            names.add(i.trim().split(" ")[0]);
        }
        return names;
    }

    private String getTableName(String cmd) {
        int begin = cmd.indexOf(StringConstants.ON) + StringConstants.ON.length();
        int end = cmd.indexOf("(", cmd.indexOf(StringConstants.ON));
        return cmd.substring(begin, end).trim();
    }

    private String getIndexName(String cmd) {
        int begin = StringConstants.CREATE_INDEX.length();
        int end = cmd.indexOf(StringConstants.ON);
        return cmd.substring(begin, end).trim();
    }
}
